<template>
  <div class="page_root" :key="queryUpdateFlag" data-page-name="项目模板项目阶段维护" data-page-identification="c_plyr5zh56v">
    <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
      <!-- begin vid_yc6z9ceswu 自定义模板_x774mzm136 -->
      <div class="body">
        <div class="title"
          ><div class="left"> 项目阶段列表 </div>
          <a-space>
            <a-button type="primary" class="add-btn" @click="handleAddOutStage">
              <template #icon><PlusSquareOutlined style="background: #77a0fc" /></template>
              新建项目阶段
            </a-button>
            <a-button type="primary" class="add-btn" @click="handleSubmit">
              <template #icon>
                <CheckSquareOutlined />
              </template>
              保存
            </a-button>
          </a-space>
        </div>

        <div class="stage-div">
          <a-form ref="templateRef2" :model="state" :rules="state.stageRules">
            <template v-if="state.templateType === '交付项目'">
              <div class="stage-item" v-for="(item, index) in state.templateStageList" :key="item.uid">
                <!--                                外层项目阶段列表-->
                <a-row :gutter="16">
                  <a-col :span="6">
                    <a-form-item label="项目阶段名称" :name="['templateStageList', index, 'stageClassify']" :rules="state.stageRules.stageName">
                      <a-input v-model:value="item.stageClassify" placeholder="请输入" :maxlength="20" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="6">
                    <a-form-item label="项目阶段序号" :name="['templateStageList', index, 'stageClassifyNo']" :rules="state.stageRules.serialNumber">
                      <a-input v-model:value="item.stageClassifyNo" placeholder="请输入" :maxlength="4" />
                      <!--                                      :disabled="!!item.templateStageId"-->
                    </a-form-item>
                  </a-col>
                  <a-col :span="12" style="padding: 0; display: flex; justify-content: end; align-items: start">
                    <a-space :size="8">
                      <a-button type="primary" class="out-btn" @click="handeAddInnerStage(index, item)">新建里程碑项目阶段 </a-button>
                      <a-popconfirm title="确定删除吗?" ok-text="确定" cancel-text="取消" @confirm="handleDeleteStage(index, item)">
                        <a-button type="primary" class="out-btn">删除父 </a-button>
                      </a-popconfirm>
                      <a-button type="link" @click="handleExpend(index, item)">
                        <template #icon>
                          <DoubleLeftOutlined v-if="item.isShow" style="color: #3875ff; rotate: 90deg" />
                          <DoubleRightOutlined v-else style="color: #3875ff; rotate: 90deg" />
                        </template>
                        {{ item.isShow ? '折叠' : '展开' }}
                      </a-button>
                    </a-space>
                  </a-col>
                  <a-form-item :name="['templateStageList', index, 'templateStageId']">
                    <a-input v-model:value="item.templateStageId" :maxlength="20" disabled type="hidden" />
                  </a-form-item>
                </a-row>
                <a-divider style="margin: 0; margin-bottom: 15px; background-color: #3875ff" />
                <!--                                外层项目阶段列表-->
                <div v-show="item.isShow">
                  <div class="lcb-item" v-for="(stage, stageIndex) in item.projectTemplateStageDtoList" :key="stage.id">
                    <a-row>
                      <a-col :span="11">
                        <a-form-item
                          label="里程碑项目阶段名称"
                          :name="[
                                                        'templateStageList',
                                                        index,
                                                        'projectTemplateStageDtoList',
                                                        stageIndex,
                                                        'stageName'
                                                    ]"
                          :rules="state.stageRules.stageName"
                        >
                          <a-input v-model:value="stage.stageName" placeholder="请输入" :maxlength="20" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="11">
                        <a-form-item
                          label="里程碑项目阶段序号"
                          :name="[
                                                        'templateStageList',
                                                        index,
                                                        'projectTemplateStageDtoList',
                                                        stageIndex,
                                                        'serialNumber'
                                                    ]"
                          :rules="state.stageRules.serialNumber"
                        >
                          <a-input v-model:value="stage.serialNumber" placeholder="请输入" :maxlength="4" />
                          <!--                                      :disabled="!!item.templateStageId"-->
                        </a-form-item>
                      </a-col>
                      <a-col :span="2" style="display: flex; justify-content: end; align-items: start">
                        <a-space :size="8">
                          <a-popconfirm
                            title="确定删除吗?"
                            ok-text="确定"
                            cancel-text="取消"
                            @confirm="
                                                            handleDeleteInnerStage(index, item, stageIndex, stage)
                                                        "
                          >
                            <a-button type="primary" class="inner-btn" size="small">
                              <template #icon>
                                <DeleteOutlined style="color: #3875ff" />
                              </template>
                              删除子
                            </a-button>
                          </a-popconfirm>
                          <!--                                                    <a-button-->
                          <!--                                                        style="margin-left: 0; padding: 0"-->
                          <!--                                                        type="link"-->
                          <!--                                                        class="template-delete"-->
                          <!--                                                        @click="handleExpend(index, item)"-->
                          <!--                                                        size="small"-->
                          <!--                                                        >{{ item.isShow ? '折叠' : '展开' }}-->
                          <!--                                                    </a-button>-->
                        </a-space>
                      </a-col>
                      <a-form-item
                        :name="[
                                                    'templateStageList',
                                                    index,
                                                    'projectTemplateStageDtoList',
                                                    stageIndex,
                                                    'templateStageId'
                                                ]"
                      >
                        <a-input v-model:value="stage.templateStageId" :maxlength="20" disabled type="hidden" />
                      </a-form-item>
                      <a-row v-show="item.isShow && state.templateType === '交付项目'">
                        <a-col :span="22">
                          <a-form-item label="目标">
                            <a-textarea v-model:value="stage.goals" placeholder="请输入" :rows="1" />
                          </a-form-item>
                        </a-col>
                        <a-col :span="22">
                          <a-form-item label="关键路径">
                            <a-textarea v-model:value="stage.crutialPath" placeholder="请输入" :rows="1" />
                          </a-form-item>
                        </a-col>
                        <a-col :span="22">
                          <a-form-item label="甲方主要角色">
                            <a-textarea v-model:value="stage.firstPartyMainRole" placeholder="请输入" :rows="1" />
                          </a-form-item>
                        </a-col>
                        <a-col :span="22">
                          <a-form-item label="甲方责任及配合事项">
                            <a-textarea v-model:value="stage.firstPartyRespAndCoopMatters" placeholder="请输入" :rows="1" />
                          </a-form-item>
                        </a-col>
                        <a-col :span="22">
                          <a-form-item label="阶段权重" :name="['templateStageList', index, 'stageWeight']" :rules="state.stageRules.stageWeight">
                            <a-input-number style="width: 100%" v-model:value="stage.stageWeight" placeholder="请输入（支持小数点后一位的整数数字）" />
                          </a-form-item>
                        </a-col>

                        <a-col :span="24">
                          <div class="role-list-div">
                            <div class="role-title-left">阶段角色列表</div>
                            <a-button type="primary" ghost size="small" @click="handleAddStageJdRule(index, stageIndex, '下方')"
                              ><template #icon> <plus-outlined /> </template>新增</a-button
                            >
                          </div>
                        </a-col>
                        <template
                          v-for="(
                                                        roleItem, roleIndex
                                                    ) in stage.projectTemplateStageRoleWeightList"
                          :key="roleIndex"
                        >
                          <a-col :span="11">
                            <a-form-item
                              label="阶段角色"
                              :name="[
                                                                'templateStageList',
                                                                index,
                                                                'projectTemplateStageDtoList',
                                                                stageIndex,
                                                                'projectTemplateStageRoleWeightList',
                                                                roleIndex,
                                                                'role'
                                                            ]"
                              :rules="state.stageRules.role"
                            >
                              <a-select v-model:value="roleItem.role" placeholder="请选择" @focus="getRolePeople" :options="directorRoleList" />
                            </a-form-item>
                          </a-col>
                          <a-col :span="11">
                            <a-form-item
                              label="权重(相加=100%)"
                              :name="[
                                                                'templateStageList',
                                                                index,
                                                                'projectTemplateStageDtoList',
                                                                stageIndex,
                                                                'projectTemplateStageRoleWeightList',
                                                                roleIndex,
                                                                'roleWeight'
                                                            ]"
                              :rules="state.stageRules.roleWeight"
                            >
                              <a-input-number style="width: 100%" v-model:value="roleItem.roleWeight" placeholder="请输入" />
                            </a-form-item>
                          </a-col>
                          <a-col :span="1" style="padding: 0">
                            <a-space :size="8" style="position: relative; top: 10px; left: 10px">
                              <div
                                class="del"
                                @click="
                                                                    handleDeleteStageJdRule(
                                                                        index,
                                                                        stageIndex,
                                                                        roleIndex
                                                                    )
                                                                "
                              ></div>
                            </a-space>
                          </a-col>
                        </template>
                        <a-divider style="margin: 0; margin-bottom: 15px; background-color: #cbcbcb" />
                      </a-row>
                    </a-row>
                  </div>
                </div>

                <!--                                <a-divider style="margin: 0; margin-bottom: 15px; background-color: #d9d9d9" />-->
              </div>
            </template>
            <template v-else>
              <a-col :span="24">
                <div class="stage-item-pt" v-for="(item, index) in state.templateStageList" :key="item.uid">
                  <div class="pt-lcb-item" v-for="(stage, stageIndex) in item.projectTemplateStageDtoList" :key="stage.id">
                    <a-row :gutter="16">
                      <a-col :span="11">
                        <a-form-item
                          label="项目阶段名称"
                          :name="[
                                                        'templateStageList',
                                                        index,
                                                        'projectTemplateStageDtoList',
                                                        stageIndex,
                                                        'stageName'
                                                    ]"
                          :rules="state.stageRules.stageName"
                        >
                          <a-input v-model:value="stage.stageName" placeholder="请输入" :maxlength="20" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="11">
                        <a-form-item
                          label="项目阶段序号"
                          :name="[
                                                        'templateStageList',
                                                        index,
                                                        'projectTemplateStageDtoList',
                                                        stageIndex,
                                                        'serialNumber'
                                                    ]"
                          :rules="state.stageRules.serialNumber"
                        >
                          <a-input v-model:value="stage.serialNumber" placeholder="请输入" :maxlength="4" />
                        </a-form-item>
                      </a-col>

                      <a-col :span="2" style="padding: 0">
                        <a-space :size="8">
                          <a-popconfirm title="确定删除吗?" ok-text="确定" cancel-text="取消" @confirm="handleDeletePtStage(index, stage)">
                            <a-button style="margin-left: 0; padding: 0" type="link" class="template-delete" size="small">删除父1 </a-button>
                          </a-popconfirm>
                          <a-button style="margin-left: 0; padding: 0" type="link" class="template-delete" @click="handleExpendPt(index, stage)" size="small"
                            >{{ stage.isShow ? '折叠' : '展开' }}
                          </a-button>
                        </a-space>
                      </a-col>
                      <a-col :span="24">
                        <div class="status-form" v-show="stage.isShow">
                          <a-col :span="24">
                            <div class="status-form-title"> <div class="status-icon"></div> 状态维护 </div>
                          </a-col>
                          <template v-for="(roleItem, roleIndex) in stage.taskStatusList" :key="roleIndex">
                            <a-row>
                              <a-col :span="10">
                                <a-form-item
                                  label="任务状态"
                                  :name="[
                                                                        'templateStageList',
                                                                        index,
                                                                        'projectTemplateStageDtoList',
                                                                        stageIndex,
                                                                        'taskStatusList',
                                                                        roleIndex,
                                                                        'taskStatus'
                                                                    ]"
                                  :rules="state.stageRules.taskStatus"
                                >
                                  <a-input v-model:value="roleItem.taskStatus" placeholder="请输入" />
                                </a-form-item>
                              </a-col>
                              <a-col :span="13" style="padding: 0">
                                <a-space :size="8" style="position: relative; top: 10px; left: 10px">
                                  <a-button
                                    size="small"
                                    @click="
                                                                            handleMoveUp(index, stageIndex, roleIndex)
                                                                        "
                                    :disabled="roleIndex === 0"
                                  >
                                    上移
                                  </a-button>
                                  <a-button
                                    size="small"
                                    @click="
                                                                            handleMoveDown(index, stageIndex, roleIndex)
                                                                        "
                                    :disabled="
                                                                            roleIndex ===
                                                                            stage.taskStatusList.length - 1
                                                                        "
                                  >
                                    下移
                                  </a-button>
                                  <div
                                    class="del"
                                    @click="
                                                                            handleDeleteStageStatus(
                                                                                index,
                                                                                stageIndex,
                                                                                roleIndex
                                                                            )
                                                                        "
                                  ></div>
                                </a-space>
                              </a-col>
                            </a-row>
                          </template>
                          <a-col :span="24">
                            <a-button size="small" type="primary" ghost @click="handleAddStageStatus(index, stageIndex)"
                              ><template #icon> <plus-outlined /> </template>新增</a-button
                            >
                          </a-col>
                        </div>
                      </a-col>
                    </a-row>
                  </div>
                </div>
              </a-col>
            </template>
          </a-form>
        </div>
      </div>
      <!-- end vid_yc6z9ceswu 自定义模板_x774mzm136 -->
    </a-spin>
  </div>
</template>
<script setup lang="tsx">
  import {
      h, ref, reactive, toRaw, markRaw, watch, computed,
      onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, onActivated, onDeactivated
    } from "vue";
    import { useRoute, useRouter } from 'vue-router';
    const router = useRouter();
    const route = useRoute();
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
    import { cloneDeep, localGet, merge, getDifferenceArray, traversalTreeStructure, checkCaseCondition, renderStringInTemplate, handleBreadcrumbJump, throttle, permission, getComponentParamsValue } from '@/utils/index';
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is';
    import dayjs from 'dayjs';
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart';
    import { message, notification, Modal } from 'ant-design-vue'
    import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate, parseSubFromDataList } from '@/utils/format';
    import colorTheme from '@/design/custom-theme.json';
    
    import UserTableRecords from '@/model/UserTableRecords';
    import { getAppBaseUrl } from '@/utils/index';
    import { sendToken } from "@/hooks/useIframeToken";
    import { useSystemStore } from "@/store/modules/system";
    const systemStore = useSystemStore();
    



      // 获取传入的流程ID和组件参数
      const props = defineProps({
            'processInstanceId': {
            type: [String,Number,Boolean],
            default: undefined,
        },
      })
      const immediateWatch = (source, callback) => {
        watch(source, callback, {deep: true,immediate: true })
      }



  /* -------------------------- 属性定义 -------------------------- */

      const setTimeOutList = [];
      const pageLoading = reactive({
        loading: false,
        tip: undefined
      });
      const authInfo = localGet('app-user-store');




      // 处理校验
      const setSubFormName =(parentInfo, name)=>{
        return [parentInfo.parents, parentInfo.cycleIndex, name];
      }


  /* ========================== 属性定义 ========================== */


  /* -------------------------- 元素数据引用 -------------------------- */


  /* ========================== 元素数据引用 ========================== */


  /* -------------------------- 页面数据 -------------------------- */


  /* ========================== 页面数据 ========================== */



  /* -------------------------- 响应 -------------------------- */

  /* ========================== 响应 ========================== */


  /* -------------------------- 函数 -------------------------- */

  /* ========================== 函数 ========================== */


  /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId,
    })

  /* ========================== 页面参数 ========================== */


  /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================


  /* ========================== 组件事件处理方法 ========================== */


  /* -------------------------- 生命周期 -------------------------- */
  // 用于参数变更后重新执行自定义指令
      const queryUpdateFlag = ref(0);
      onMounted(() => { ;

    });

    onUnmounted(() => {
      // 销毁定时器
      setTimeOutList.forEach(({ repeat, timer }) => {
        repeat ?  clearInterval(timer): clearTimeout(timer);
      });
    });

  /* ========================== 生命周期 ========================== */


  /* -------------------------- 数据关联处理 -------------------------- */





  /* -------------------------- 表单数据同步 -------------------------- */
  /* ========================== 表单数据同步 ========================== */

  /* ========================== 数据关联处理 ========================== */


  /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

  /* ========================== 不同组件自定义的处理逻辑 ========================== */


  // ================================定制化逻辑========================================
  const validateStageCode = (rule, value) => {
          if (value !== undefined && value !== null) {
              const reg = new RegExp(/^(0|([1-9][0-9]*))(\.\d{1,2})?$/)
              if (!reg.test(value)) {
                  return Promise.reject('请输入小数点后两位以内的正数数字')
              } else {
                  return Promise.resolve()
              }
          } else {
              return Promise.reject('请输入项目阶段序号')
          }
      }
      const validateQzCode = (rule, value) => {
          if (value !== undefined && value !== null) {
              // 正则表达式：匹配正整数或小数点后最多一位的正数
              const reg = new RegExp(/^(0|([1-9][0-9]*))(\.[0-9])?$/)
              if (!reg.test(value)) {
                  return Promise.reject('请输入小数点后一位的正整数')
              } else {
                  return Promise.resolve()
              }
          } else {
              return Promise.resolve()
          }
      }
      const validateJsqz = (rule, value) => {
          const str = rule.field
          const match = str.match(
              /templateStageList\.(\d+)\.projectTemplateStageDtoList\.(\d+)\.projectTemplateStageRoleWeightList/
          )
          if (!match) {
              return Promise.reject('字段格式不正确')
          }

          const parentIndex = match[1]
          const childIndex = match[2]

          // 校验是否为正数，最多一位小数
          const reg = /^(0|[1-9][0-9]*)(\.[0-9])?$/
          if (value !== undefined && value !== null) {
              if (!reg.test(value)) {
                  return Promise.reject('请输入小数点后一位的正整数')
              }
          } else {
              return Promise.reject('请输入阶段权重')
          }

          // 获取当前阶段下所有角色的权重列表
          const currentStage = state.templateStageList[parentIndex]?.projectTemplateStageDtoList?.[childIndex]
          const weightList = currentStage?.projectTemplateStageRoleWeightList

          if (!Array.isArray(weightList)) {
              return Promise.reject('数据结构异常')
          }

          const totalWeight = weightList.reduce((sum, roleItem) => {
              return sum + (parseFloat(roleItem.roleWeight) || 0)
          }, 0)

          if (totalWeight !== 100) {
              return Promise.reject('阶段角色的权重总和必须为100')
          }

          return Promise.resolve()
      }

      const validateJsjs = (rule, value) => {
          const str = rule.field
          console.log('field:', str)

          const match = str.match(
              /templateStageList\.(\d+)\.projectTemplateStageDtoList\.(\d+)\.projectTemplateStageRoleWeightList/
          )
          if (!match) {
              return Promise.reject('字段格式不正确')
          }

          const parentIndex = match[1]
          const childIndex = match[2]

          if (!value) {
              return Promise.reject('请选择阶段角色')
          }

          const currentStage = state.templateStageList[parentIndex]
          const currentChild = currentStage?.projectTemplateStageDtoList?.[childIndex]

          if (!currentChild || !Array.isArray(currentChild.projectTemplateStageRoleWeightList)) {
              return Promise.reject('数据结构异常')
          }

          const arr = currentChild.projectTemplateStageRoleWeightList.filter(item => item.role === value)

          if (arr.length > 1) {
              return Promise.reject('该角色已经存在，请选择其他角色')
          }

          return Promise.resolve()
      }

      // 任务状态校验
      const validateStatus = (rule, value) => {
          if (!value) {
              return Promise.resolve() // 允许为空
          }

          // 正则表达式：匹配汉字和数字
          const regex = /^[\u4e00-\u9fa5\d]+$/

          if (!regex.test(value)) {
              return Promise.reject('只能输入汉字或数字')
          }

          return Promise.resolve()
      }
      onMounted(() => {
          const urlParams = new URLSearchParams(window.location.search)
          state.versionId = urlParams.get('versionId')
          state.templateId = urlParams.get('templateId')
          state.templateType = urlParams.get('templateType')
          state.taskType = urlParams.get('taskType')

          getStageList(
              state.templateId,
              result => {
                  if (!state.templateStageList.length) {
                      state.templateStageList = [
                          {
                              stageClassify: undefined,
                              stageClassifyNo: undefined,
                              templateStageId: undefined,
                              isShow: true,
                              projectTemplateStageDtoList: [
                                  {
                                      ...innerItem,
                                      isShow: true,
                                      taskStatusList: [], // ✅ 确保子 stage 的 taskStatusList 也是独立的
                                      projectTemplateStageRoleWeightList: [] // ✅ 确保子 stage 的 taskStatusList 也是独立的
                                  }
                              ],
                              uid: $guid()
                          }
                      ]
                  } else {
                      state.templateStageList = state.templateStageList.map(item => ({
                          ...item,
                          isShow: true
                      }))
                  }
                  state.projectStageVisible = true
              },
              state.taskType
          )
      })
      const state = reactive({
          templateId: undefined,
          versionId: undefined,
          templateType: undefined,
          taskType: undefined,
          milepostLoading: false,
          // 项目阶段列表
          templateStageList: [],
          projectStageVisible: false,
          stageRules: {
              stageName: [{ required: true, message: '请输入项目阶段名称', trigger: 'blur' }],
              serialNumber: [{ required: true, validator: validateStageCode, trigger: 'blur' }],
              stageWeight: [{ required: false, validator: validateQzCode, trigger: 'blur' }],
              role: [{ required: true, validator: validateJsjs, trigger: 'blur' }],
              roleWeight: [{ required: true, validator: validateJsqz, trigger: 'blur' }],
              taskStatus: [{ required: false, validator: validateStatus, trigger: 'blur' }]
          }
      })

      // 查询模板下的项目阶段
      function getStageList(id, callback, type) {
          get(
              `/solution-ppm/api/v2/built-in-system-ppm/project/template/${id}/stage/list/v2?stageType=${type}&versionId=${
                  state.versionId || ''
              }`
          ).then(res => {
              state.templateStageList = res.data.map(item => {
                  return {
                      ...item,
                      isShow: true
                  }
              })
              callback && callback()
          })
      }
      function $guid(prefix) {
          function s4() {
              const baseNumber = 0x10000
              const radix = 16
              return Math.floor((1 + Math.random()) * baseNumber)
                  .toString(radix)
                  .substring(1)
          }

          return `${prefix ? `${prefix}-` : ''}${s4()}${s4()}-${s4()}`
      }
      // 删除交付外部阶段
      const handleDeleteStage = (index, item) => {
          if (state.templateStageList.length <= 1) {
              return
          }
          console.log(item, 'das')
          checkTaskExist(item.templateStageId, result => {
              if (result) {
                  state.projectStageVisible = false
                  Modal.confirm({
                      title: '提示',
                      centered: true,
                      content: '该阶段下包含任务，是否确认删除',
                      onOk() {
                          state.templateStageList.splice(index, 1)
                          state.projectStageVisible = true
                      },
                      onCancel() {
                          state.projectStageVisible = true
                      }
                  })
                  return
              }
              state.templateStageList.splice(index, 1)
          })
      }
      // 删除交付内部阶段
      const handleDeleteInnerStage = (index, item, stageIndex, stage) => {
          console.log(index, 'index')
          console.log(item, 'item')
          console.log(stageIndex, 'stageIndex')
          if (state.templateStageList[index].projectTemplateStageDtoList.length <= 1) {
              return
          }
          console.log(stage, 'das')
          checkTaskExist(stage.templateStageId, result => {
              if (result) {
                  state.projectStageVisible = false
                  Modal.confirm({
                      title: '提示',
                      centered: true,
                      content: '该阶段下包含任务，是否确认删除',
                      onOk() {
                          state.templateStageList[index].projectTemplateStageDtoList.splice(stageIndex, 1)
                          state.projectStageVisible = true
                      },
                      onCancel() {
                          state.projectStageVisible = true
                      }
                  })
                  return
              }
              state.templateStageList[index].projectTemplateStageDtoList.splice(stageIndex, 1)
          })
      }
      // 删除平台阶段
      const handleDeletePtStage = (index, item) => {
          console.log(item, 'das')
          checkTaskExist(item.templateStageId, result => {
              if (result) {
                  state.projectStageVisible = false
                  Modal.confirm({
                      title: '提示',
                      centered: true,
                      content: '该阶段下包含任务，是否确认删除',
                      onOk() {
                          state.templateStageList.splice(index, 1)
                          state.projectStageVisible = true
                      },
                      onCancel() {
                          state.projectStageVisible = true
                      }
                  })
                  return
              }
              state.templateStageList[0].projectTemplateStageDtoList.splice(index, 1)
          })
      }
      // 查询项目阶段下是否包含任务
      function checkTaskExist(id, callback) {
          console.log(id)
          if (!id) {
              // 新建
              callback(false)
              return
          }
          get(`/solution-ppm/api/v2/built-in-system-ppm/project/template/stage/${id}/${state.versionId}/task_exist`).then(
              ({ data }) => {
                  callback(data)
              }
          )
      }
      function handleExpend(index, item) {
          console.log(item)
          item.isShow = !item.isShow
          nextTick(() => {})
      }
      function handleExpendPt(index, item) {
          console.log(item)
          item.isShow = !item.isShow
          nextTick(() => {})
      }
      const directorRoleList = ref([])
      function getRolePeople() {
          get('/solution-ppm/api/v2/built-in-system-ppm/project/template/role/list').then(data => {
              directorRoleList.value = data.data.map(item => {
                  return {
                      label: item.roleName,
                      value: item.roleName
                  }
              })
          })
      }
      //     新建外层项目阶段
      const outItem = {
          'stageClassify': undefined,
          'stageClassifyNo': undefined,
          projectTemplateStageDtoList: []
      }
      const innerItem = {
          'stageName': undefined,
          'serialNumber': undefined,
          taskStatusList: []
      }
      function handleAddOutStage() {
          if (state.templateType === '交付项目') {
              state.templateStageList.push({ ...outItem, isShow: true })
          } else {
              state.templateStageList.push({
                  'stageClassify': undefined,
                  'stageClassifyNo': undefined,
                  projectTemplateStageDtoList: [{...innerItem}]
              })
              console.log(state.templateStageList);
          }
      }
      // 新建阶段下的角色
      const handleAddStageJdRule = (index, stageIndex) => {
          console.log(index, 'index')
          console.log(stageIndex, 'stageIndex')
          console.log(
              state.templateStageList[index].projectTemplateStageDtoList[stageIndex].projectTemplateStageRoleWeightList,
              ' state.templateStageList[index].projectTemplateStageDtoList[stageIndex]'
          )
          state.templateStageList[index].projectTemplateStageDtoList[stageIndex].projectTemplateStageRoleWeightList?.push(
              {
                  role: undefined,
                  roleWeight: 0
              }
          )
      }
      // 删除阶段下的角色
      // 删除阶段
      const handleDeleteStageJdRule = (index, stageIndex, roleIndex) => {
          // if (state.templateStageList[index].projectTemplateStageRoleWeightList?.length <= 1) {
          //     return
          // }
          state.templateStageList[index].projectTemplateStageDtoList[
              stageIndex
          ].projectTemplateStageRoleWeightList?.splice(roleIndex, 1)
      }
      // 新建状态
      const handleAddStageStatus = (index, stageIndex) => {
          if (!state.templateStageList[index].projectTemplateStageDtoList[stageIndex].taskStatusList) {
              state.templateStageList[index].projectTemplateStageDtoList[stageIndex].taskStatusList = []
          }
          state.templateStageList[index].projectTemplateStageDtoList[stageIndex].taskStatusList.push({
              taskStatus: undefined // 注意这里应该是 taskStatus 而不是 status，以匹配你的模板
          })
      }

      // 删除状态
      const handleDeleteStageStatus = (index, stageIndex, roleIndex) => {
          state.templateStageList[index].projectTemplateStageDtoList[stageIndex].taskStatusList?.splice(roleIndex, 1)
      }
      //     新增里程碑阶段
      function handeAddInnerStage(index) {
          state.templateStageList[index].isShow = true
          state.templateStageList[index].projectTemplateStageDtoList.push({
              stageName: undefined,
              serialNumber: undefined,
              goals: undefined,
              crutialPath: undefined,
              firstPartyMainRole: undefined,
              firstPartyRespAndCoopMatters: undefined,
              stageWeight: undefined,
              projectTemplateStageRoleWeightList: [],
              taskStatusList: [],
              uid: $guid()
          })
      }
      const handleMoveUp = (index, stageIndex, roleIndex) => {
          if (roleIndex === 0) return

          const list = state.templateStageList[index].projectTemplateStageDtoList[stageIndex].taskStatusList
          const temp = list[roleIndex - 1]
          list[roleIndex - 1] = list[roleIndex]
          list[roleIndex] = temp
      }

      const handleMoveDown = (index, stageIndex, roleIndex) => {
          const list = state.templateStageList[index].projectTemplateStageDtoList[stageIndex].taskStatusList
          if (roleIndex >= list.length - 1) return

          const temp = list[roleIndex + 1]
          list[roleIndex + 1] = list[roleIndex]
          list[roleIndex] = temp
      }

      //     保存
      const templateRef2 = ref(null)
      function handleSubmit() {
          console.log(state.templateStageList)
          templateRef2.value.validateFields().then(res => {
              console.log(state.templateStageList)
              state.milepostLoading = true
              updateStageList(state.templateId, state.templateStageList)
          })
      }
      // 项目阶段更新
      function updateStageList(id, params, callback) {
          post(`/solution-ppm/api/v2/built-in-system-ppm/project/template/${id}/stage/latest/v2`, {
              dataList: params,
              versionId: state.versionId,
              stageType: state.taskType
          })
              .then(res => {
                  if (res.status === 'fail') {
                      message.error(res.message)
                      return
                  }
                  message.success(res.message)
                  getStageList(
                      state.templateId,
                      result => {
                          if (!state.templateStageList.length) {
                              console.log('走这里')
                              state.templateStageList = [
                                  {
                                      stageClassify: undefined,
                                      stageClassifyNo: undefined,
                                      templateStageId: undefined,
                                      isShow: true,
                                      projectTemplateStageDtoList: [
                                          {
                                              ...innerItem,
                                              isShow: true,
                                              taskStatusList: [], // ✅ 确保子 stage 的 taskStatusList 也是独立的
                                              projectTemplateStageRoleWeightList: [] // ✅ 确保子 stage 的 taskStatusList 也是独立的
                                          }
                                      ],
                                      uid: $guid()
                                  }
                              ]
                          } else {
                              state.templateStageList = state.templateStageList.map(item => ({
                                  ...item,
                                  isShow: false
                              }))
                          }
                          state.projectStageVisible = true
                      },
                      state.taskType
                  )
              })
              .finally(() => {
                  state.milepostLoading = false
              })
      }
</script>
<style lang="less" scoped>
  .page_root {
  width: 100%;
  height: 100%;
  overflow: auto;
  }
  .page_root :deep(.@{ant-prefix}-spin-nested-loading),
  .page_root :deep(.@{ant-prefix}-spin-container)
   {
      height: 100%;
  }
  .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper)
   {
      display: flex;
      flex-flow: column nowrap;
      justify-content: flex-start;
  }
  .page_root :deep(.@{ant-prefix}-table)
   {
    flex: auto;
    overflow: auto;
  }
  .table-moreBtn_down {
    overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 100px;
  }

  .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
    background: #ebf1ff;
  }

  /*  表格树结构样式处理，展开按钮层级增加*/
  :deep(.@{ant-prefix}-table-row-expand-icon) {
    z-index: 1;
  }
  /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
  :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 15px !important;
    width: calc(100% - 15px);
  }
  :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 30px !important;
    width: calc(100% - 30px);
  }
  :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 45px !important;
    width: calc(100% - 45px);
  }
  :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 60px !important;
    width: calc(100% - 60px);
  }

  /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
  :deep(.@{ant-prefix}-transfer-list)
   {
      height: 100%;
      width: 50%;
  }


  /*样式*/
      .page_root {
          overflow-y: hidden;
          height: 100%;
      }
      .body {
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          gap: 16px;
      }
      .stage-div {
          flex: 1;
          overflow-y: auto;
      }
      .stage-div :deep(.ant3-form-item-label) {
          width: 150px;
      }
      .stage-item {
          padding: 24px;
          margin-top: 16px;
          background: #ffffff;
          border-radius: 4px;
      }
      .stage-item:first-child {
          margin-top: 0;
      }
      .pt-lcb-item {
          margin-bottom: 16px;
          padding: 24px;
          margin-bottom: 16px;
          background: #ffffff;
          border-radius: 4px;
      }
      .title {
          display: flex;
          justify-content: space-between;
          align-items: center;
      }
      .left {
          height: 16px;
          line-height: 16px;
          padding-left: 8px;
          border-left: 4px solid #3875ff;
          font-size: 16px;
          color: #000000;
          letter-spacing: 0;
          font-weight: 600;
      }
      .add-btn {
          background: #6090ff;
      }
      .status-form-title {
          display: flex;
          align-items: center;
          font-size: 14px;
          color: #262626;
          font-weight: 600;
      }
      .status-form {
          background: #f5f8ff;
          border: 1px solid rgba(56, 117, 255, 0.5);
          border-radius: 5px;
          padding: 12px 20px;
      }
      .status-form :deep(.ant3-form-item-label) {
          width: 130px;
      }
      .mb-icon,
      .status-icon,
      .version-icon {
          width: 16px;
          height: 16px;
          background-size: cover;
          margin-right: 4px;
      }
      .mb-icon {
          background-image: url('@/assets/images/31112c303f54c29e5165744705a4705a.png');
      }
      .status-icon {
          background-image: url('@/assets/images/f89a840c579feb3f330e96e7de02c1f8.png');
      }
      .version-icon {
          background-image: url('@/assets/images/d2b844c19f9bf01977c7d73fb7de1476.png');
      }
      .role-list-div {
          padding-left: 8px;
          height: 16px;
          line-height: 16px;
          display: flex;
          justify-content: space-between;
          font-size: 16px;
          color: #262626;
          letter-spacing: 0;
          font-weight: 600;
          border-left: 4px solid #3875ff;
          margin-bottom: 16px;
      }
      .out-btn {
          background: rgba(56, 117, 255, 0.09);
          border: 1px solid #3875ff;
          border-radius: 4px;
          color: #3875ff;
      }
      .inner-btn {
          background: rgba(56, 117, 255, 0.09);
          border-radius: 4px;
          color: #3875ff;
          border: none;
      }

      .del {
          background-size: cover;
          width: 16px;
          height: 16px;
          cursor: pointer;
      }
      .del {
          background-image: url('@/assets/images/80c373960957a45c2b94645f214b46c0.png');
      }
      /*样式*/
</style>